import streamlit as st
import requests
import json


def page_templates():
    if st.button("← 返回主界面"):
        st.session_state.update({"page": "page_main"})
        st.rerun()
    st.title("评分模板管理")

    try:
        resp = requests.get("http://127.0.0.1:8001/scoring_template/list", timeout=10)
        items = resp.json().get("data", []) if resp.ok else []
    except Exception as e:
        st.error(f"获取模板失败：{e}")
        items = []

    st.subheader("模板列表")
    for it in items:
        cols = st.columns([2, 3, 1, 1])
        with cols[0]:
            st.write(it.get("template_key", ""))
        with cols[1]:
            st.write(it.get("weights_json", ""))
        with cols[2]:
            st.write("默认" if it.get("default_flag", 0) == 1 else "")
        with cols[3]:
            eid = f"del_{it.get('id')}"
            if st.button("删除", key=eid):
                try:
                    payload = {"id": it.get("id")}
                    data = {"json_data_str": json.dumps(payload, ensure_ascii=False)}
                    r = requests.post("http://127.0.0.1:8001/scoring_template/delete", data=data, timeout=10)
                    if r.ok and r.json().get("data") == "ok":
                        st.success("已删除")
                        st.rerun()
                    else:
                        st.error(r.text)
                except Exception as e:
                    st.error(str(e))

    st.subheader("新增/更新模板")
    template_key = st.text_input("模板键")
    weights_json = st.text_area("权重JSON", value='{"专业能力":0.5,"沟通能力":0.2,"项目经验":0.3}')
    description = st.text_area("描述", value="")
    default_flag = st.checkbox("默认模板", value=False)

    cols2 = st.columns(2)
    with cols2[0]:
        if st.button("新增模板"):
            try:
                payload = {
                    "template_key": template_key,
                    "weights_json": weights_json,
                    "description": description,
                    "default_flag": 1 if default_flag else 0
                }
                data = {"json_data_str": json.dumps(payload, ensure_ascii=False)}
                r = requests.post("http://127.0.0.1:8001/scoring_template/add", data=data, timeout=10)
                if r.ok and r.json().get("data"):
                    st.success("新增成功")
                    st.rerun()
                else:
                    st.error(r.text)
            except Exception as e:
                st.error(str(e))
    with cols2[1]:
        upd_id = st.text_input("更新ID")
        if st.button("更新模板"):
            try:
                payload = {
                    "id": int(upd_id or 0),
                    "update_fields": {
                        "template_key": template_key,
                        "weights_json": weights_json,
                        "description": description,
                        "default_flag": 1 if default_flag else 0
                    }
                }
                data = {"json_data_str": json.dumps(payload, ensure_ascii=False)}
                r = requests.post("http://127.0.0.1:8001/scoring_template/update", data=data, timeout=10)
                if r.ok and r.json().get("data") == "ok":
                    st.success("更新成功")
                    st.rerun()
                else:
                    st.error(r.text)
            except Exception as e:
                st.error(str(e))
